<template>
  <el-dialog
    :model-value="AuthShow"
    :title="AuthTitle"
    width="50%"
    @close="Cancel"
  >
    <el-tree
      empty-text="加载中..."
      ref="treeRef"
      :data="Authlist"
      :show-checkbox="true"
      node-key="id"
      highlight-current
      :default-expand-all="true"
      :props="defaultProps"
      v-if="Authlist"
      :default-checked-keys="DefArr"
    >
    </el-tree>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="Cancel">取消</el-button>
        <el-button type="primary" @click="Confirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, Ref, ref, defineProps } from "vue";
import { ElTree, ElMessage } from "element-plus";

import apis from "@/http/apis";
interface Tree {
  id: number;
  label: string;
  children?: Tree[];
}

let prop = defineProps({
  AuthShow: Boolean,
  AuthTitle: String,
  AuthData: {
    type: Object,
    default: {},
  },
});
// console.log(prop.AuthData, "666");

let Authlist: Ref = ref([]); //树节点对象
let DefArr: Ref = ref([]); //选中节点id数组
const defaultProps = {
  //树型对象的属性绑定
  children: "children",
  label: "authName",
};
//定义递归函数来遍历出当前点击对象中已经被选中的节点
const isChecked = (tree: Idata, arr: Object[]) => {
  //如果没有children属性说明是最终子节点
  if (!tree.children) {
    return arr.push(tree.id);
  }
  tree.children.forEach((item: any) => {
    isChecked(item, arr);
  });
};

//初始请求权限列表
const initAuthlist = async () => {
  let res = await apis.getRoleAuth();
  Authlist.value = (res as Idata).data;
  // console.log(Authlist.value);
  // 利用递归遍历出当前节点已经被选中的权限
  DefArr.value = isChecked(prop.AuthData, DefArr.value);
};
initAuthlist();

//定义关闭弹窗的自定义事件
const emits = defineEmits(["closePop"]);
//关闭和取消触发的事件
const Cancel = () => {
  DefArr.value = [];
  // console.log("自定义事件触发");

  emits("closePop", false);
};
let halfcheck = ref([]); //目前半选中
let Allcheck = ref([]); //目前全选中
let data = ref({}); //分配权限请求的参数对象
const treeRef = ref(); //树组件实例
//确定处理函数
const Confirm = async () => {
  //调用组件实例方法获取所有半选中和全选中的id
  halfcheck.value = treeRef.value.getHalfCheckedKeys();
  Allcheck.value = treeRef.value.getCheckedKeys();
  // console.log(halfcheck.value, "半选中");
  // console.log(Allcheck.value, "全选中");
  //因为要求参数数组为字符串
  let CheckedArrString = [...halfcheck.value, ...Allcheck.value].join(",");
  // console.log(CheckedArrString);
  data.value = {
    roleId: prop.AuthData.id,
    rids: CheckedArrString,
  };
  const res: any = await apis.addAuth(data.value);
  if (res.meta.status == 200) {
    ElMessage({
      message: "添加权限成功",
      type: "success",
    });
  } else {
    ElMessage({
      message: "添加失败",
      type: "error",
    });
  }
  initAuthlist();
  Cancel();
};
</script>

<style lang="less" scoped></style>
